package io.renren.modules.crud.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.tencent.common.pojo.Result;
import com.tencent.common.pojo.StatusCode;
import io.renren.common.utils.RandomNickNameUtils;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.crud.entity.RegisterVerify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.crud.dao.UsersDao;
import io.renren.modules.crud.entity.UsersEntity;
import io.renren.modules.crud.service.UsersService;


@Service("usersService")
public class UsersServiceImpl extends ServiceImpl<UsersDao, UsersEntity> implements UsersService {

    @Autowired
    UsersDao usersDao;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    CouponDao couponDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UsersEntity> page = this.page(
                new Query<UsersEntity>().getPage(params),
                new QueryWrapper<UsersEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Result<UsersEntity> getAmount(Integer userId) {
        QueryWrapper<UsersEntity> usersEntityQueryWrapper = new QueryWrapper<>();
        usersEntityQueryWrapper.eq("user_id",userId);
        UsersEntity usersEntity = usersDao.selectOne(usersEntityQueryWrapper);
        if (usersEntity.getLoanAmount() == null) {
            Long amount = calculateAmount(usersEntity.getCreditScore());
            usersEntity.setLoanAmount(amount);
            usersDao.update(usersEntity,usersEntityQueryWrapper);

        }
        return new Result<>(StatusCode.OK,"查询成功",true,usersEntity);
    }

    @Override
    public Result login(UsersEntity userEntity) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("nick_name",userEntity.getNickName());
        UsersEntity user = usersDao.selectOne(wrapper);
        if(null != user){
            if(user.getPassword().equals(userEntity.getPassword())){
                return new Result(StatusCode.OK,"用户登录成功",true);
            }
            return new Result(StatusCode.ERROR,"密码错误",false);
        }
        return new Result(StatusCode.ERROR,"用户名错误",false);
    }

    @Override
    public Result getUserInfo(String userId) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        UsersEntity user = usersDao.selectOne(wrapper);
        return new Result(StatusCode.OK,"用户信息查询成功",true,user);
    }


    @Override
    public Result changeHeadImg(UsersEntity usersEntity) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        usersDao.update(usersEntity,wrapper);
        return new Result(StatusCode.OK,"更改头像成功",true);
    }

    @Override
    public Result changePhone(UsersEntity usersEntity) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        usersDao.update(usersEntity,wrapper);
        return new Result(StatusCode.OK,"更改手机号成功",true);
    }

    @Override
    public Result changeNickName(UsersEntity usersEntity) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        usersDao.update(usersEntity,wrapper);
        return new Result(StatusCode.OK,"更改昵称成功",true);
    }

    @Override
    public String uploadImg(MultipartFile file) {
        File file1 = OSSClientUtil.multipartFileToFile(file);
        String name = UUID.randomUUID().toString();
        String[] strings = OSSClientUtil.uploadObject2OSS(file1, "userHeadImg/" + name);
        String user_pic = "https://1908aoss.oss-cn-qingdao.aliyuncs.com/"+strings[1];
        return user_pic;
    }

    @Override
    public Result getVerifyCode(String phone) {
        String code = RandomUtil.randomString(4);
        System.out.println(code);
        //SendMsgUtils.sendMsg(phone,code);
        return new Result(StatusCode.OK,"获取验证码成功",true,code);
    }

    @Override
    public Result register(RegisterVerify registerVerify) {
        String nickName = RandomNickNameUtils.verifyUserName(3, 3);
//        File file = new File("D:\\SpringCloudIdea\\demo\\VastFinancialProject\\vast-service\\vast-financial-service\\src\\main\\resources\\static\\userInitImg\\userImg.png");
//        String ImagePath = UUID.randomUUID().toString();
//        String[] strings = OSSClientUtil.uploadObject2OSS(file, "userHeadImg/"+ImagePath);
        String user_pic = "https://1908aoss.oss-cn-qingdao.aliyuncs.com/userHeadImg/f2e63557-5725-472b-bde4-d5d25a279481/2022-05-22/2146eb73339f45dfb4ab9072c83eac11.png";
        UsersEntity usersEntity = new UsersEntity(0, user_pic, registerVerify.getPassword(), registerVerify.getPhone(), 0, null, null, nickName, null, null, null, null,null);
        usersDao.insert(usersEntity);
        return new Result(StatusCode.OK,"注册成功",true);
    }

    @Override
    public Result loginSSO(String username, String password) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("nick_name",username);
        UsersEntity usersEntity = usersDao.selectOne(wrapper);
        if(null != usersEntity){
            return new Result(StatusCode.OK,"用户名正确",true,usersEntity);
        }
        return new Result(StatusCode.ERROR,"用户名错误",false);
    }

    @Override
    public void updateUserIntegral(Integer userId) {
        QueryWrapper<UsersEntity> usersEntityQueryWrapper = new QueryWrapper<>();
        usersEntityQueryWrapper.eq("user_id",userId);
        UsersEntity usersEntity = usersDao.selectOne(usersEntityQueryWrapper);
        usersEntity.setIntegral(usersEntity.getIntegral()-10);
        usersDao.update(usersEntity,usersEntityQueryWrapper);
    }

    @Override
    public Result getUserIntegral(Integer userId) {
        UsersEntity usersEntity = usersDao.selectById(userId);
        return new Result(StatusCode.OK,"查询成功",true,usersEntity.getIntegral());
    }

    @Override
    public Result<UsersEntity> userById(Integer userId) {
        return new Result<>(StatusCode.OK,"查询成功",true,usersDao.selectById(userId));
    }

    @Override
    public Result getUserInfo(String userId) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        UsersEntity user = usersDao.selectOne(wrapper);
        return new Result(StatusCode.OK,"用户信息查询成功",true,user);
    }

    @Override
    public Result changeHeadImg(UsersEntity usersEntity) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        usersDao.update(usersEntity,wrapper);
        return new Result(StatusCode.OK,"更改头像成功",true);
    }

    @Override
    public Result changePhone(UsersEntity usersEntity) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        usersDao.update(usersEntity,wrapper);
        return new Result(StatusCode.OK,"更改手机号成功",true);
    }

    @Override
    public Result changeNickName(UsersEntity usersEntity) {
        QueryWrapper<UsersEntity> wrapper = new QueryWrapper<>();
        usersDao.update(usersEntity,wrapper);
        return new Result(StatusCode.OK,"更改昵称成功",true);
    }

    @Override
    public Result getUserSingInDays(Integer userId) {
        UsersEntity usersEntity = usersDao.selectById(userId);
        return new Result(StatusCode.OK,"查询成功",true,usersEntity.getCheckDays());
    }

    @Override
    public Result cliSign(Integer userId) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        Object sign = hashOperations.get("sign", userId.toString());
        // 判断是否签到
        if (sign==null || sign.equals("")) {
            // 修改状态
            hashOperations.put("sign",userId.toString(),"1");
            // 更新数据
            QueryWrapper<UsersEntity> usersEntityQueryWrapper = new QueryWrapper<>();
            usersEntityQueryWrapper.eq("user_id",userId);
            UsersEntity usersEntity = usersDao.selectOne(usersEntityQueryWrapper);
            usersEntity.setIntegral(usersEntity.getIntegral()+5);
            usersEntity.setCheckDays(usersEntity.getCheckDays()+1);
            usersDao.update(usersEntity,usersEntityQueryWrapper);
            return new Result(StatusCode.OK,"更新数据成功",true);
        }
        return new Result(StatusCode.OK,"更新数据失败",false);
    }

    @Override
    public Result<List<CouponEntity>> getCoupon(Integer userId) {
        QueryWrapper<CouponEntity> usersEntityQueryWrapper = new QueryWrapper<>();
        usersEntityQueryWrapper.eq("user_id",userId);
        List<CouponEntity> couponEntities = couponDao.selectList(usersEntityQueryWrapper);
        return new Result<>(StatusCode.OK,"查询成功",true,couponEntities);
    }

    @Override
    public Result idCardVerify(Integer userId) {
        UsersEntity usersEntity = usersDao.selectById(userId);
        if (usersEntity.getCardId() != null && !usersEntity.getCardId().equals("")) {
            return new Result(StatusCode.OK,"验证成功",true);
        }
        return new Result(StatusCode.OK,"验证失败",false);
    }


    @Override
    public String uploadImg(MultipartFile file) {
        File file1 = OSSClientUtil.multipartFileToFile(file);
        String name = UUID.randomUUID().toString();
        String[] strings = OSSClientUtil.uploadObject2OSS(file1, "userHeadImg/" + name);
        String user_pic = "https://1908aoss.oss-cn-qingdao.aliyuncs.com/"+strings[1];
        return user_pic;
    }

    /**
     * 计算额度
     * @return
     */
    public Long calculateAmount(Integer creditScore){
        if (creditScore >= 10 && creditScore <= 20) {
            return 1000L;
        }
        if (creditScore >= 20 && creditScore <= 30) {
            return 2000L;
        }
        if (creditScore >= 30 && creditScore <= 40) {
            return 3000L;
        }
        if (creditScore >= 40 && creditScore <= 50) {
            return 4000L;
        }
        if (creditScore >= 50 && creditScore <= 60) {
            return 5000L;
        }
        if (creditScore >= 60 && creditScore <= 70) {
            return 6000L;
        }
        if (creditScore >= 70 && creditScore <= 80) {
            return 7000L;
        }
        if (creditScore >= 80 && creditScore <= 90) {
            return 8000L;
        }
        if (creditScore >= 90 && creditScore <= 100) {
            return 10000L;
        }
        return null;
    }

    /**
     * 每天23点清除签到状态
     */
    @Scheduled(cron = "0 0 23 * * ?")
    public void clearStatus(){
        List<UsersEntity> usersEntities = usersDao.selectList(null);
        HashOperations hashOperations = redisTemplate.opsForHash();
        for (UsersEntity usersEntity : usersEntities) {
            hashOperations.put("sign",usersEntity.getUserId().toString(),"");
        }
    }

}